# Spring Boot 配置 Knife4j
# 一、引入 maven
<!-- 引入 knife4j 文档-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi2-spring-boot-starter</artifactId>
<version>4.1.0</version>
</dependency>
1
2
3
4
5
6
2
3
4
5
6
# 二、配置 application.yml
knife4j:
# 开启增强配置
enable: true
setting:
# 是否启用 Host
enable-host: true
# 启用 Host 地址
enable-host-text: "https://yunhu.wiki/api"
# 配置账号密码访问文档
basic:
enable: true
username: admin
password: 123456
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 三、knife4j 配置类
import com.github.xiaoymin.knife4j.spring.extension.OpenApiExtensionResolver;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
/**
* 配置 Knife4j 接口文档
*
* @author: yunhu
* @date: 2023/7/30
*/
@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfiguration {
private final OpenApiExtensionResolver openApiExtensionResolver;
@Autowired
public Knife4jConfiguration(OpenApiExtensionResolver openApiExtensionResolver) {
this.openApiExtensionResolver = openApiExtensionResolver;
}
@Bean(value = "defaultApi2")
public Docket defaultApi2() {
String groupName = "yunhu-library";
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.groupName(groupName)
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build()
.extensions(openApiExtensionResolver.buildExtensions(groupName));
return docket;
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.description("# swagger-bootstrap-ui-demo RESTful APIs")
.termsOfServiceUrl("http://www.library.wiki")
.version("1.0")
.build();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# 四、常用 api 注解
@Api(tags = "后台书籍管理模块") // 控制层类的注解,接口的分组名称
@ApiOperation("创建书籍") // 控制层类中的方法注解
@ApiModel(value = "BookEntity", description = "书籍实体类") // 实体类的注解
@ApiModelProperty(value = "书籍 id") // 字段的注解
1
2
3
4
5
6
7
2
3
4
5
6
7